$(function () {
    init_exEmpData();
    init_deptList();
    init_currentDeptList();
    $("body").on('click','[data-stopPropagation]',function (e) {e.stopPropagation();});
    $("#cExGroud").select2({placeholder:"选择客户意向"});
    $("#cExGroud").on("change", function(e) {
        var yixiang = $("#cExGroud").val();
        var yArray = new Array();
        $.each(yixiang,function (index,val) {yArray.push(val);});
        var conver = yArray.join(",");
        $("#cExGroudselect").val(conver);
        $JuXue.refreshTable("bigExEmpTable");
    });
    $("#deptSelect").select2({placeholder:"选择最初分配部门"});
    $("#deptSelect").on("change", function(e) {
        var yixiang = $("#deptSelect").val();
        var yArray = new Array();
        $.each(yixiang,function (index,val) {yArray.push(val);});
        var conver = yArray.join(",");
        $("#selectDeptId").val(conver);
        $JuXue.refreshTable("bigExEmpTable");
        //if(conver!=""){init_personList(conver);}
    });
    $("#currentDeptS").select2({placeholder:"选择当前跟进部门"});
    $("#currentDeptS").on("change", function(e) {
        var yixiang = $("#currentDeptS").val();
        var yArray = new Array();
        $.each(yixiang,function (index,val) {yArray.push(val);});
        var conver = yArray.join(",");
        $("#selectCurrentDeptId").val(conver);
        $JuXue.refreshTable("bigExEmpTable");
        if(conver!=""){init_personList(conver);}
    });
    /**人员筛选**/
    $("#personSelect").select2({placeholder:"选择人员"});
    $("#personSelect").on("change", function(e) {
        var deptid = $("#personSelect").val();
        var yArray = new Array();
        $.each(deptid,function (index,val) {yArray.push(val);});
        var conver = yArray.join(",");
        $("#selectPersonId").val(conver);
        $JuXue.refreshTable("bigExEmpTable");
    }); /**地区筛选**/

    $("#placeSelect").select2({placeholder:"选择地区"});
    $("#placeSelect").on("change", function(e) {
        var zone = $("#placeSelect").val();
        var yArray = new Array();
        $.each(zone,function (index,val) {yArray.push(val);});
        var conver = yArray.join(",");
        $("#selectPlaceId").val(conver);
        $JuXue.refreshTable("bigExEmpTable");
    });
    /**筛选时间**/
    $("#exEmp_advance span").html(moment().subtract("days",29).format("YYYY-MM-DD")+" - "+moment().format("YYYY-MM-DD"));
    $('#exEmp_advance').daterangepicker({
        timePicker: true, //显示时间
        timePicker24Hour: true, //时间制
        timePickerSeconds: true, //时间显示到秒
        startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
        endDate: moment(new Date()), //设置结束器日期
        maxDate: moment(new Date()), //设置最大日期
        "opens": "center",
        ranges: {
            '今天': [moment(), moment()],'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '上周': [moment().subtract(6, 'days'), moment()],
            '前30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        showWeekNumbers: true,
        locale: {
            format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
            applyLabel: '确定', //确定按钮文本
            cancelLabel: '取消', //取消按钮文本
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            firstDay: 1
        },
    }).on('apply.daterangepicker', function(ev, picker) {
        var starttime = picker.startDate.format('YYYY-MM-DD');
        var endtime = picker.endDate.format('YYYY-MM-DD');
        $("#exEmp_advance span").html(starttime+" - "+endtime);
        $("#ext_starttime").val(starttime);
        $("#ext_endtime").val(endtime);
        $JuXue.refreshTable("bigExEmpTable");
    });
});
/**初始化部门筛选*/
function init_deptList() {
    var url = ctx+"dept/list";
    $.post(url,{},function (r) {
        if(r.length>0){
            $("#deptSelect").empty();
            $.each(r,function (index,val) {$("#deptSelect").append("<option value='"+val.deptId+"'>"+val.deptName+"</option>")});
        }
    });
}

/**初始化当前跟进部门筛选*/
function init_currentDeptList() {
    var url = ctx+"dept/list";
    $.post(url,{},function (r) {
        if(r.length>0){
            $("#currentDeptS").empty();
            $.each(r,function (index,val) {$("#currentDeptS").append("<option value='"+val.deptId+"'>"+val.deptName+"</option>")});
        }
    });
}

/**初始化人员筛选*/
function init_personList(deptId) {
    var url = ctx+"user/selectUserByDept";
    $.post(url,{deptId:deptId},function (r) {
        if(r.length>0){
            $("#personSelect").empty();
            $.each(r,function (index,val) {$("#personSelect").append("<option value='"+val.userUuid+"'>"+val.nickname+"</option>")});
        }
    });
}
/**初始化数据**/
function init_exEmpData() {
    var settings = {
        url: ctx + "seaExtension/list",
        pageSize: 15,
        pageList: [10,50, 100,300,500,1000],
        showColumns: true,
        showToggle: true,
        queryParams: function(params) {
            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                cExIntern: $("#changeinteproject").val(),
                cExGroud:  $("#cExGroudselect").val(),
                starttime: $("#ext_starttime").val(),
                endtime:   $("#ext_endtime").val(),
                cExDept:   $("#selectDeptId").val(),
                cExStatus: $("#ext_disatre").val(),
                cExReceiver:$("#selectPersonId").val(),
                cExzone    :$("#selectPlaceId").val(),
                cExStage   :$("#selectStage").val(),
                cExCurrentDept:$("#selectCurrentDeptId").val()
            };
        },
        columns: [{
            checkbox: true,
        }, {
            field: 'cExName',
            title: '客户名称',
            width: 150,
            clickToSelect:false,
            class:'text-center',
            formatter:function (value, row, index) {
                return "<a href='javascript:void(0)' onclick='viewExEmpDetail(this)' data-id='"+row.cExId+"'>"+value+"</a>";
            }
        }, {
            field: 'cExMobile',
            title: '手机'
        }, {
            field: 'cExWechat',
            title: '微信'
        }, {
            field: 'cExCreator',
            title: '创建人'
        },{
            field: 'cExIntern',
            title: '意向项目'
        },{
            field: 'cExGroud',
            title: '意向等级'
        }, {
            field: 'cExDept',
            title: '最初分配部门'
        }, {
            field: 'cExCurrentDept',
            title: '当前跟进部门'
        }, {
            field: 'cExReceiver',
            title: '当前跟进人'
        },{
            field: 'cExTime',
            title: '创建时间'
        }, {
            field: 'cExMethod',
            title: '分配方式',
            formatter:function (value, row, index) {
                if (value == 2){return "<span class='color-green'>手动</span>";
                }else {return "<span class='color-blue'>自动</span>";}
            }
        },{
            field: 'cExStatusjin',
            title: '状态',
            formatter:function (value, row, index) {
                if (value == 1){return "<span class='color-green'>普通</span>";
                }else if (value == 2){return "<span class='color-red'>紧急</span>";
                }else{return "<span class='color-blue'>暂缓</span>";}
            }
        },{
            field: 'cExInit',
            title: '最初访问',
            visible:false
        },{
            field: 'cExRetime',
            title: '领取时间',
            visible:false
        },{
            field: 'cExIsdelete',
            title: '领取时间差',
            formatter:function (value, row, index) {
                if(row.cExRetime == null){return "0 秒";}
                return new Date( new Date(row.cExRetime)- new Date(row.cExTime)).getTime()/1000+" 秒";
            },
            visible:false
        },{
            field: 'dealtime',
            title: '成交时间',
            formatter:function (value, row, index) {
                if(row.dealtime == null){return "尚未成交";}
                return value;
            },
            visible:false
        },{
            field: 'cExKey',
            title: '访问关键词',
            visible:false
        },{
            field: 'cExChanel',
            title: '访问渠道',
            visible:false

        },{
            field: 'cExzone',
            title: '地域',
            visible:false
        },{
            field: 'cExZiSource',
            title: '咨询来源',
            visible:false
        },{
            field: 'cExRemarks',
            title: '备注',
            visible:false
        }],
        onClickCell:function(field, value, row, $element){
            if(field == "cExName"){
                return ;
            }else{
                var a = ".theme-panel", b = "active";
                //$(a).hasClass(b) ? $(a).removeClass(b) : $(a).addClass(b)
                $(a).addClass(b);
                $("#selectTheme").show();
                var selected = $("#bigEmpTable").bootstrapTable('getSelections');
                var selected_length = selected.length;
                $("#sutomeSelect").text(selected_length+1);
            }
        },
        onUncheck:function (row,ele) {
            var selected = $("#bigEmpTable").bootstrapTable('getSelections');
            var selected_length = selected.length;
            if (!selected_length) {
                var a = ".theme-panel", b = "active";
                $(a).removeClass(b);
                $("#selectTheme").hide();
            }
            $("#sutomeSelect").text(selected_length+1);
        },
        onCheck:function (row,ele) {
            var selected = $("#bigExEmpTable").bootstrapTable('getSelections');
            var selected_length = selected.length;
            if (!selected_length) {
                var a = ".theme-panel", b = "active";
                $(a).removeClass(b);
                $("#selectTheme").hide();
            }else{
                var a = ".theme-panel", b = "active";
                $(a).addClass(b);
                $("#selectTheme").show();
            }
            $("#sutomeSelect").text(selected_length);
        },
        onUncheck:function (rows) {
            var selected = $("#bigExEmpTable").bootstrapTable('getSelections');
            var selected_length = selected.length;
            if (!selected_length) {
                var a = ".theme-panel", b = "active";
                $(a).removeClass(b);
                $("#selectTheme").hide();
            }else{
                var a = ".theme-panel", b = "active";
                $(a).addClass(b);
                $("#selectTheme").show();
            }
            $("#sutomeSelect").text(selected_length);
        },
        onCheckAll:function (rows) {
            var a = ".theme-panel", b = "active";
            $(a).addClass(b);
            $("#selectTheme").show();
            $("#sutomeSelect").text(rows.length);
        },
        onUncheckAll:function (rows) {
            var a = ".theme-panel", b = "active";
            $(a).removeClass(b);
            $("#selectTheme").hide();
        }
    };
    $JuXue.initTable('bigExEmpTable', settings);
}

/**
 * 切换意向项目
 * **/
function changeinteproject(btn){
    $("#changeinteproject").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data-click");
    $("#changeinteproject").val(project);
    //动态加载
    $JuXue.refreshTable("bigExEmpTable");
}
/**切换分配状态**/
function extEmpDisatre(btn) {
    $("#disatre").find("button").each(function () {$(this).removeClass("btn-primary");});
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data-click");
    $("#ext_disatre").val(project);
    //动态加载
    $JuXue.refreshTable("bigExEmpTable");
}
/**切换成交方式**/
function extEmpIsDeal(btn) {
    $("#dealbutn").find("button").each(function () {$(this).removeClass("btn-primary");});
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data-click");
    $("#selectStage").val(project);
    //动态加载
    $JuXue.refreshTable("bigExEmpTable");
}

/**切换创建时间**/
function extEmpTime(btn) {
    var data_cliak = $(btn).attr("data-click");
    if(data_cliak === "selft"){
        $("#exEmp_advance").removeClass("hidden");
        $("#ext_starttime").val(moment().subtract("days",29).format("YYYY-MM-DD"));
        $("#ext_endtime").val(moment().format("YYYY-MM-DD"));
    }else{
        $("#exEmp_advance").addClass("hidden");
        $("#ext_starttime").val("");
        $("#ext_endtime").val("");
    }
    $("#extcustTime").find("button").each(function () {$(this).removeClass("btn-primary");});
    $(btn).addClass("btn-primary");
    //动态加载
    $JuXue.refreshTable("bigExEmpTable");
}
/**新增客户*/
function addCustomer_ex(){
    $.post(ctx+"seaExtension/loadAdd",{},function (r) {$("#myCustomer-modal").empty().append(r).modal('show').draggable();});
}
/**加载客户资料*/
function viewExEmpDetail(btn) {
    var ids = $(btn).attr("data-id");
    if (ids == "" || ids == undefined){$JuXue.n_danger("获取客户资料失败");return }
     $("#customer_ids").val(ids);
    $.post(ctx+"seaExtension/exEmpDetail",{},function (r) {
        $("#myCustomer-modal").empty().append(r).modal('show').draggable();
    })
}
/**导出客户资料**/
function exportExtEmpInfo() {
    var ids = $("#bigExEmpTable").bootstrapTable("getSelections");
    var ids_arr = "";
    if (!ids.length) {$JuXue.n_warning("请勾选需要导出的客户信息！");return;}
    for (var i = 0; i < ids.length; i++) {
        ids_arr += ids[i].cExId;
        if (i !== (ids.length - 1)) ids_arr += ",";
    }
    $.post(ctx+"seaExtension/getAllExEmpByids",{"ids":ids_arr},function(r){
        if (r.code === 0) {
            window.open("file/download?fileName=" + r.msg + "&delete=" + true);
        } else {$JuXue.n_warning(r.msg);}
    });
}

/**删除推广客户**/
function deleteExtEmp() {
    var ids = $("#bigExEmpTable").bootstrapTable("getSelections");
    var ids_arr = "";
    if (!ids.length) {$JuXue.n_warning("请勾选需要删除的客户信息！");return;}
    for (var i = 0; i < ids.length; i++) {
        ids_arr += ids[i].cExId;
        if (i !== (ids.length - 1)) ids_arr += ",";
    }
    $JuXue.confirm({
        text: "确定删除当前选择的客户？",
        confirmButtonText: "确定删除"
    }, function() {
        $.post(ctx+"seaExtension/delAllExEmpByids",{ids:ids_arr},function(r){
            if (r.code === 0) {
                $JuXue.n_success(r.msg);
                $JuXue.refreshTable("bigExEmpTable");
            } else {
                $JuXue.n_warning(r.msg);
            }
        });
    });


}